package com.xxz.terminal;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class InformationModificationActivity extends AppCompatActivity {
    DBHelper dbHelper;
    SQLiteDatabase db;
    EditText editText;
    String information;
    DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_modification);

        //展示未修改的信息
        Intent intent = getIntent();
        information = intent.getStringExtra("information");
        String xinxi = intent.getStringExtra("xinxi");

        TextView textView = findViewById(R.id.changetitle);
        editText = findViewById(R.id.editchange);

        textView.setText(information);
        editText.setText(xinxi);
        if(information.equals("修改密码")){
            editText.setHint("请在此输入新密码");
        }

        dbHelper = new DBHelper(this);
        db = dbHelper.getWritableDatabase();

    }
    //将修改后的数据写入数据库
    public void save(View btn){

        String xinxi = editText.getText().toString();
        if(xinxi.isEmpty()&&information.equals("修改密码")){
            Toast.makeText(this, "不能将密码置为空", Toast.LENGTH_SHORT).show();
        }
        else {
            SharedPreferences sp = getSharedPreferences("userinformation",MODE_PRIVATE);
            String user_id  = sp.getString("user_id",null);

            if(information.equals("修改密码")) {
                information = "password";//此处注意要用equals,而不是==
            }
            else if(information.equals("昵称")) information = "nickname";
            else if(information.equals("座右铭")) information = "motto";//将title与数据库字段名称对应


            ContentValues values = new ContentValues();
            values.put(information,xinxi);
            //更新数据库
            db.update("userinformation",values,"user_id=?",new String[]{user_id});

            //更新sp
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(information,xinxi);
            editor.apply();

            //返回设置页面
            Intent intent = new Intent(this,MainPageActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("index",10);
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            finish();
            startActivity(intent);
        }

    }
    public void back(View btn){
        finish();
    }
}